import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Address.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';

class AddressPage extends StatefulWidget {
  @override
  _AddressPageState createState() => _AddressPageState();
}

class _AddressPageState extends StateWithLifecycle<AddressPage> {
  var _item = [];
  EasyRefreshController _easyRefreshController = EasyRefreshController();

  @override
  void onResume() {
    super.onResume();
    _getAddress();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Theme.of(context).canvasColor,
        leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              Routers.router.pop(context);
            }),
        automaticallyImplyLeading: false,
        title: Text(
          '收货地址',
          style: TextStyle(fontSize: 18),
        ),
      ),
      body: EasyRefresh.custom(
        enableControlFinishRefresh: true,
        header: CommWidget.commHeader(),
        emptyWidget: _item.length == 0 ? CommWidget.nullWidget() : null,
        controller: _easyRefreshController,
        enableControlFinishLoad: true,
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
              return Column(
                children: <Widget>[
                  _itemWidget(_item[index]),
                  Container(
                    height: 8,
                    color: Theme.of(context).canvasColor,
                  ),
                ],
              );
            }, childCount: _item.length),
          )
        ],
        onRefresh: () => _getAddress(),
      ),
      bottomSheet: _addWidget(),
    );
  }

  ///
  Widget _itemWidget(Address address) {
    return Card(
      elevation: 4,
      margin: EdgeInsets.only(left: 10, right: 10, bottom: 4),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _userWidget(address),
            SizedBox(height: 6),
            _addrWidget(address),
            Divider(),
            _mageWidget(address),
          ],
        ),
      ),
    );
  }

  ///用户名手机号
  Widget _userWidget(Address address) {
    String phone = address.telephone;
    if (phone.length > 8) {
      phone = phone.substring(0, 3) + "****" + phone.substring(7);
    }
    return Row(
      children: <Widget>[
        Text(
          address.realName,
          style: TextStyle(
            fontSize: 17,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(width: 20),
        Text(
          phone,
          style: TextStyle(
            fontSize: 17,
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  ///地址
  Widget _addrWidget(Address address) {
    String addr =
        "${address.province} ${address.city} ${address.area} ${address.street}";
    return Text(
      addr,
      style: TextStyle(fontSize: 16),
    );
  }

  ///管理
  Widget _mageWidget(Address address) {
    return Row(
      children: <Widget>[
        Offstage(
          offstage: !address.defAdds,
          child: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.only(left: 2, right: 2),
            decoration: BoxDecoration(
              color: Color(0xFFFDEEE8),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              '默认',
              style: TextStyle(
                fontSize: 10,
                color: Color(0xffE25413),
              ),
            ),
          ),
        ),
        Expanded(flex: 1, child: Container()),
        GestureDetector(
          onTap: () {
            _delDialog(context, address.addressId);
          },
          child: Row(
            children: <Widget>[
              Image.asset(
                Comm.IMG_DEL,
                width: 18,
                height: 18,
              ),
              Text("删除"),
            ],
          ),
        ),
        SizedBox(width: 20),
        GestureDetector(
          onTap: () {
            var jsons = jsonEncode(Utf8Encoder().convert(json.encode(address)));
            String url = '${Routers.PAGE_ADDADRS}?address=$jsons';
            Routers.router.navigateTo(context, url,
                transition: TransitionType.inFromRight);
          },
          child: Row(
            children: <Widget>[
              Image.asset(
                Comm.IMG_EDIT,
                width: 18,
                height: 18,
              ),
              Text("编辑"),
            ],
          ),
        ),
      ],
    );
  }

  ///添加地址按钮
  Widget _addWidget() {
    return GestureDetector(
      child: Container(
        height: 48,
        alignment: Alignment.center,
        width: double.infinity,
        color: Colors.red,
        child: Text(
          "添加地址",
          style: TextStyle(
            fontSize: 18,
            color: Colors.white,
          ),
        ),
      ),
      onTap: () {
        Routers.router.navigateTo(context, Routers.PAGE_ADDADRS,
            transition: TransitionType.inFromRight);
      },
    );
  }

  _delDialog(BuildContext context, String addressId) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("温馨提示"),
            content: Text("您确定要删除该条记录吗？"),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text("取消"),
              ),
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                  _delAddress(addressId);
                },
                child: Text("确定"),
              ),
            ],
          );
        });
  }

  ///删除地址
  Future _delAddress(String addressId) async {
    String url = "${Api.URL_ADDRESS_DEL}?addressId=$addressId";
    Http.get(url, successCallBack: (data) {
      _easyRefreshController.callRefresh();
    }, errorCallBack: (error) {
      Toast.show(error);
    });
  }

  ///获取地址列表
  Future _getAddress() async {
    Http.get(Api.URL_ADDRESS_LIST, successCallBack: (data) {
      List list = json.decode(data).map((m) => Address.fromJson(m)).toList();
      _item.clear();
      _easyRefreshController.finishRefresh();
      setState(() {
        _item.addAll(list);
      });
    }, errorCallBack: (error) {
      _easyRefreshController.finishRefresh();
    });
  }
}
